<template>
	<view class="article-editor" ref="uv-back-top">
		<view class="editor-box">
			<document :maxCount="100" :accept="only" uploadText="可以多图,最多6张" ref="document" v-model="referImages">
			</document>
			<view
				style="border-bottom: 1px solid #eee;padding: 5px;width: 99%;display: flex;flex-direction: row;justify-content: space-between;align-items: center;">
				<view v-if="sCont">
					<view style="display: flex;padding: 0px 5px;">
						<view v-if="sInfo" style="width: auto;height: auto;">
							<uploads maxCount="50" class="uvUpload" accept="file" mode="aspectFill" :width="65"
								:height="64" :fileList="fileList" :deletable="false">
							</uploads>
						</view>
						<view
							style="display: flex; justify-content: flex-start; flex-wrap: wrap; align-items: flex-start;width: auto;height: auto;">
							<view v-for="(itm,idx) in uploads" :key="idx"
								style="position: relative;margin-right: 10px;margin-bottom: 5px;">
								<view class="item_dsh" @click="uploads.splice(idx, 1)">
									<uv-icon size="12" color="#FFF" bold name="close"></uv-icon>
								</view>
								<view v-if="type=='video'">
									<uv-swiper style="width: 100px;" :height="65" :list="[{
									url: itm.url,
									poster: itm.url+'?x-oss-process=video/snapshot,t_3000,f_jpg,w_800,h_600',
									type: 'video'
									}]" keyName="url" :autoplay="false"></uv-swiper>
								</view>
								<uv-image v-else @click="preview(itm.url)" mode="fill" :src="itm.url" width="65px"
									height="64px" radius="6px"></uv-image>
							</view>
							<view v-if="uploads.length<50" class="uploadImage" @click="prefixclick(3)">
								<view
									style="background-color: #F4F5F7;border-radius: 4px;border: 1px solid #FFAAFF;width: 64px;height: 63px;display: flex;flex-direction: column;justify-content: center;align-items: center;">
									<uv-icon style="opacity: 0.4;"
										:name="type=='video'?'/static/index/svg/video.svg':'/static/index/svg/picture.svg'"
										size="43"></uv-icon>
									<view style="font-size: 11px;">{{type=='video'?'视频':'图片'}}</view>
								</view>
							</view>
							<document :accept="type" mode="aspectFill" :maxCount="50" uploadText="可以多文件,最多50个"
								ref="document3" v-model="uploads" @resdata="e=>parentMethod(e,'custom')">
							</document>
						</view>
					</view>
				</view>
				<view style="margin-right: 5px;">
					<view v-if="cover.length<1" class="uploadImage" @click="prefixclick(4)">
						<view
							style="font-size: 15px;background-color: #F4F5F7;border-radius: 4px;border: 1px solid #FFAAFF;width: 64px;height: 63px;display: flex;flex-direction: column;justify-content: center;align-items: center;">
							<uv-icon style="opacity: 0.4;" name="camera-fill" size="43"></uv-icon>
							<view style="font-size: 11px;">自定义封面</view>
						</view>
					</view>
					<view v-else style="position: relative;">
						<view class="item_dsh" @click="cover.splice(0, 1)">
							<uv-icon size="12" color="#FFF" bold name="close"></uv-icon>
						</view>
						<uv-image @click="preview(cover[0].url)" mode="fill" :src="cover[0].url" width="65px"
							height="64px" radius="6px"></uv-image>
					</view>
					<document :accept="'image'" mode="aspectFill" :maxCount="1" :uploadText="'封面'" ref="document4"
						v-model="cover">
					</document>
				</view>
			</view>
			<uv-input @focus="$emit('focus')" border="bottom" fontSize="22px" maxlength="50" v-model="name"
				placeholder="请输入标题（建议30字以内）">
			</uv-input>
			<view>
				<uv-text style="opacity: 0;height: 2px;" lines="1" :text="fill"></uv-text>
				<sp-editor style="height: calc(100vh - 400px);width: 100%;flex-wrap: wrap;overflow: auto;"
					ref="spEditor" :toolbar-config="toolbarConfig" placeholder="请输入正文，请输入至少一张图片作为封面！" @init="initEditor"
					@input="inputOver" @upinImage="upinImage" @uploadFile="uploadFile" @overMax="overMax"
					@addLink="addLink" @exportHtml="exportHtml" @blur="inputBlur" @focus="inputFocus"></sp-editor>
			</view>
			<!-- ,'direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck' -->
			<view style="border-top: 1px solid #eee;padding:  5px 0px;">
				<view v-if="!sCont" style="width: 100%;">
					<uv-textarea style="margin: 0px 5px;" @focus="$emit('focus')" placeholder="请输入描述" v-model="des"
						:maxlength="maxlength*10" count autoHeight></uv-textarea>
				</view>
				<view v-for="(ite,inde) in link" :key="inde">
					<view style="margin: 5px;display: flex;justify-content: flex-start;align-items: center;">
						<view style="font-size: 14px;">&nbsp;{{inde+1}}链接：</view>
						<uv-textarea style="width: 50%;" autoHeight placeholder="请输入链接标题"
							v-model="ite.title"></uv-textarea>
						<uv-textarea style="width: 50%;" autoHeight placeholder="请输入链接网址"
							v-model="ite.url"></uv-textarea>
						<uv-icon v-if="inde==0" style="cursor: pointer;" size="28" name="plus-circle"
							@click="link.push({title:'',url:''});"></uv-icon>
						<uv-icon v-else style="cursor: pointer;" size="28" name="minus-circle"
							@click="link.splice(inde, 1)"></uv-icon>
					</view>
				</view>

				<view style="margin: 5px;display: flex;justify-content: flex-start;align-items: center;">
					<view style="font-size: 14px;">&nbsp;标签：</view><uv-textarea @focus="$emit('focus')" autoHeight
						:placeholder="'请输入自定义标签用,分隔（建议'+maxlength+'字内）'" v-model="dynamicTags" @change="changetag"
						:maxlength="maxlength+100"></uv-textarea>
				</view>
				<view v-if="dynamicTags"
					style="width: 100%;max-height: 100px;overflow: auto;;padding:5px 5px 0px 5px;display: flex;justify-content: flex-start;align-items: center;flex-wrap: wrap;">
					<view style="margin-right: 10px;margin-bottom: 5px;" v-for="(name, index) in tags" :key="index">
						<uv-tags :text="'#'+name" closePlace="right" closable @close="handleClose(name)">
						</uv-tags>
					</view>
				</view>
			</view>
			<view class="editor-button">
				<view class="editor-button_left">
					<view></view>
					<view></view>
					<view>说明：&nbsp;保存&nbsp;后才能发布或预览</view>
				</view>
				<view class="editor-button_right">
					<view style="margin-right: 10px;">
						<el-tooltip
							style="font-size: 13px;display: flex;justify-content: flex-start;align-items: center;"
							effect="dark" content="保存后可以发布或预览" placement="top-start">
							<!-- <uv-button size="mini" type="primary" text="确 定"></uv-button> -->
							<uv-button style="font-weight: bold;" type="success" :plain="true" size="mini" round
								@click="confirm">保 存</uv-button>
							<!-- <view style="border-radius: 5px;border:1px solid #eee;padding: 1px 5px;text-align: center;"
								@click="confirm">
								保 存
							</view> -->
						</el-tooltip>
						<!-- <view
							style="width: 30px;margin-top: 5px;font-size: 13px;border-radius: 5px;border:1px solid #eee;padding: 1px 5px;"
							@click="preview(type,value)">
							预 览
						</view> -->
						<!-- <uv-button size="mini" round @click="confirm">保 存</uv-button> -->
						<uv-button style="margin-top: 1px;font-weight: bold;" size="mini" round :disabled="!value"
							@click="preview(type,value)">预 览</uv-button>
					</view>
					<el-tooltip style="font-size: 14px;display: flex;justify-content: flex-start;align-items: center;"
						effect="dark" content="发布到首页" placement="top-start">
						<el-popover v-if="articleInfo&&articleInfo.show==2&&value" placement="top" width="160"
							v-model="visible">
							<p>确定要取消发布吗？</p>
							<div style="text-align: right; margin: 0">
								<el-button size="mini" type="text" @click="visible = false">取消</el-button>
								<el-button type="primary" size="mini" @click="release()">确定</el-button>
							</div>
							<el-link slot="reference" style="color:#8E949C;">取消发布</el-link>
						</el-popover>
						<!-- style="height: 50px;" -->
						<uv-button v-else :disabled="value?disabled:true" type="primary" text="发 布" @click="release()">
							<view style="font-size: 20px;">
								发 布
							</view>
						</uv-button>
					</el-tooltip>
				</view>
			</view>
		</view>
		<el-dialog>
			<view slot="title" style="display: flex;justify-content: flex-start;align-items: center;">
				<view style="margin-right: 10px;">
					发布到首页
				</view>
			</view>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="">确 定</el-button>
			</span>
		</el-dialog>
		<uv-toast style="height: 0;" ref="toast"></uv-toast>
		<uv-back-top style="height: 0;" :scroll-top="scrollTop"></uv-back-top>
		<!-- <tabbars :prop-value="'mapping'"></tabbars> -->
	</view>
</template>

<script>
	// 引入
	import tabbars from '@/components/tabbar/tabbar.vue';
	import headers from '@/components/header/header.vue';
	import uploads from '@/components/upload/upload.vue';
	import document from '@/components/document/document.vue';
	import Md5 from 'js-md5';
	import config from '@/common/config'
	import {
		getFlowName,
		getScrollName,
		scrollName,
		flowName,
		uploadFile,
		getUser,
		userName
	} from '@/common/api.js';
	export default {
		components: {
			// 注册组件
			tabbars,
			headers,
			document,
			uploads
		},
		model: {
			prop: 'value', // 对应 props 的属性名
			event: 'input' // 触发事件名
		},
		props: {
			value: [String, Array],
			minWidth: {
				type: [Number, String],
				default: 1
			},
			aside: {
				type: Boolean,
				default: false
			},
			deepColor: {
				type: String,
				default: '#4D4D4D'
			},
			shallowColor: {
				type: String,
				default: '#808080'
			},
			lightColor: {
				type: String,
				default: '#ccc'
			},
			aicurrent: {
				type: Number,
				default: 0
			},
			type: {
				type: String,
				default: 'article'
			},
			articleInfo: Object,
		},
		data() {
			return {
				fill: config.fill,
				env: config.env,
				scrollTop: 0,
				editorIns: null,
				editorCtx: null,
				name: config.env == 'development' ? '' : '',
				tags: [],
				des: '',
				dynamicTags: '',
				inputVisible: false,
				inputValue: '',
				maxlength: 100,
				htmlData: '',
				inputSave: false,
				writing: '',
				tabbarsValue: 'fusion',
				disabled: false,
				toolbarConfig: {
					keys: [],
					excludeKeys: [
						'indentInc', 'indentDec', 'direction', 'date', 'fontFamily', 'listCheck'
					],
					iconSize: '18px'
				},

				visible: false,
				allList: null,
				fileList: [],
				link: [{
					title: '',
					url: ''
				}],
				show: 0,
				uploads: [],
				custom: [],
				referImages: [],
				editorCtx: null,
				only: '',
				aesDate: '',
				cover: '',
			}
		},
		computed: {
			sInfo() {
				let fs;
				this.fileList = [];
				if (JSON.stringify(this.articleInfo) != '{}') {
					if (this.articleInfo.type != "fusion") {
						fs = this.articleInfo;
					}
				}
				return fs;
			},
			sCont() {
				if (this.sInfo) {
					return true;
				}
				if (this.type == 'video' || this.type == 'image') {
					return true;
				}
				return false;
			},
		},
		watch: {
			// 监听data数据的变化
			articleInfo: {
				handler: function(newVal, oldVal) {
					this.preRender(newVal);
				},
				deep: true
			},
			referImages: {
				handler: function(newVal, oldVal) {
					if (newVal && newVal[0] && newVal[0].url) {
						for (var index = 0; index < newVal.length; index++) {
							var element = newVal[index];

							if (element.mimeType.includes('video')) {
								this.editorCtx.insertImage({
									src: element.url +
										'?x-oss-process=video/snapshot,t_3000,f_jpg,w_800,h_600',
									width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
									alt: element.url, // 携带视频真实地址
									success: function() {
										uni.hideLoading()
									}
								})
							} else {
								this.editorCtx.insertImage({
									src: element.url,
									width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
									success: function() {
										uni.hideLoading()
									}
								})
							}
						}
					}
				},
				deep: true
			},
			// fileList: {
			// 	handler: function(newVal, oldVal) {
			// 		// console.log(newVal);
			// 	},
			// 	deep: true
			// },
			htmlData: {
				handler: function(newVal, oldVal) {
					if (JSON.stringify(newVal) != '{}') {
						let url = this.getImageUrls(newVal);
						if (!this.cover[0] && url[0]) {
							this.cover = [{
								url: url[0]
							}]
						}
					}
				},
				deep: true
			},
		},
		mounted() {
			this.tabbarsValue = this.pages();
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
			// #ifdef APP-NVUE
			this.scrollTop = e.detail.scrollTop;
			// #endif
		},
		beforeDestroy() {
			// 在页面销毁前断开socket连接
			this.confirm();
		},
		methods: {
			prefixclick(i) {
				this.$nextTick(() => {
					this.$refs['document' + i].visible();
				});
			},
			parentMethod(value, name) {
				this[name] = [];
				for (var index = 0; index < value.length; index++) {
					this[name].push({
						type: value[index].mimeType,
						url: value[index].url,
					});
				}
			},
			// 提取所有图片 URL
			getImageUrls(html) {
				const imgReg = /<img[^>]+src="([^">]+)"/gi; // 正则匹配 src 属性
				const urls = [];
				let match;
				while (match = imgReg.exec(html)) {
					urls.push(match[1]); // 提取第一个捕获组（URL）
				}
				return urls;
			},
			uv_video(e) {
				let src = [];
				if (e?.content && e?.content[0]) {
					e = e.content[0];
				}
				if (e?.data && e?.data[0]) {
					src = [{
						url: e.data[0].url,
						type: 'video',
					}];
				}
				if (e?.videoUrl) {
					src.push({
						url: e.videoUrl,
						type: 'video',
						poster: e.imageUrl
					});
				}
				if (e?.musics) {
					for (var i = 0; i < e.musics.length; i++) {
						src.push({
							url: e.musics[i].videoUrl || e.musics[i].audioUrl,
							type: 'video',
							poster: e.musics[i].imageUrl
						});
					}
				}
				return src;
			},
			uv_image(e) {
				let src = [];
				if (e?.content && e?.content[0]) {
					e = e.content[0];
				}
				if (e?.data && e?.data[0]) {
					src = [{
						url: e.data[0].url,
					}];
				}
				if (e?.imageUrl) {
					src = [{
						url: e.imageUrl,
					}];
				}
				if (e?.videoFirstFrame) {
					src = [{
						url: e.videoFirstFrame,
					}];
				}
				if (e?.targetImage) {
					src = [{
						url: e.targetImage,
					}];
				}
				if (e?.images) {
					for (var i = 0; i < e.images.length; i++) {
						src.push({
							url: e.images[i]
						});
					}
				}
				if (e?.url) {
					src = [{
						url: e.url,
					}];
				}
				if (e?.musics) {
					for (var i = 0; i < e.musics.length; i++) {
						src.push({
							url: e.musics[i].imageUrl
						});
					}
				}
				return src;
			},
			pages() {
				var pages = getCurrentPages() // 获取栈实例
				let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
				let currentPage = pages[pages.length - 1]['$page']['fullPath'] //当前页面路径(带参数)
				return currentPage.split('/')[2];
			},
			tagNormalizer(e) {
				return e.map(tag => {
					if (typeof tag === 'string') return tag.trim().toLowerCase();
					if (tag.toString) return tag.toString().trim().toLowerCase();
					return '';
				})
			},
			async release() {
				var that = this;
				this.disabled = true;
				var datahash = Md5(JSON.stringify(await this.datahand()));
				if (datahash != this.aesDate) {
					await this.confirm();
				}
				userName('flow', {
					id: this.value,
				}, {
					custom: {
						auth: true,
						toast: true,
					},
				}).then(e => {
					this.$refs.toast.show({
						message: e == 2 ? '发布成功！' : '取消发布！',
					});
					this.$emit('refresh', uni.$uv.guid(20));
					this.visible = false;
					this.disabled = false;
				}).catch(e => {
					console.log(e);
					this.disabled = false;
				})

			},
			updateValue(newVal) { // 触发事件更新父组件变量
				this.$emit('input', newVal);
			},
			// 主函数：从任意结构中提取图片 URL
			extractImageUrls(data) {
				var that = this;
				const results = new Set(); // 使用 Set 自动去重
				const visited = new WeakSet(); // 防止循环引用
				// 递归遍历函数
				function traverse(obj) {
					if (!obj || visited.has(obj)) return;
					// 标记已访问对象（避免循环引用）
					if (typeof obj === 'object' && obj !== null) {
						visited.add(obj);
					}
					// 处理字符串（核心匹配逻辑）
					if (typeof obj === 'string') {
						if (that.isImageUrl(obj)) {
							results.add(obj);
						}
						return;
					}
					// 处理数组
					if (Array.isArray(obj)) {
						obj.forEach(itm => traverse(itm));
						return;
					}
					// 处理对象
					if (typeof obj === 'object') {
						Object.values(obj).forEach(itm => traverse(itm));
					}
				}
				traverse(data);
				return Array.from(results); // 转为数组返回
			},
			// 判断字符串是否为图片 URL
			isImageUrl(str) {
				// 匹配图片扩展名 // 匹配完整图片 URL // 匹配 base64 图片
				return /\.(jpe?g|png|gif|bmp|webp|svg)(\?[^\\s]*)?$/i.test(str) ||
					/^(https?:\/\/.*\.(?:png|jpg|jpeg|gif|webp))/i.test(str) ||
					/^data:image\/([a-zA-Z]*);base64,/.test(
						str);
			},
			handleClose(e) {
				this.tags.splice(this.tags.indexOf(e), 1);
				this.dynamicTags = this.tags.join(",");
			},
			changetag(e) {
				let cTags = e.replaceAll("，", ",");
				this.tags = cTags.split(',').filter(Boolean);
			},
			blur() {
				uni.$uv.debounce(this.confirm, 1500);
			},
			async preview(type, value) {
				if (value) {
					if (await this.confirm()) {
						this.routed('/pages/index/details?type=' + type + '&id=' + value)
					}
				} else {
					uni.previewImage({ // 预览图片
						urls: [type],
						fail() {
							this.$uv.toast('预览图片失败')
						},
					});
				}
			},
			async datahand(e = null, a = null) {
				let cover = '';
				if (this.cover[0]) {
					cover = this.cover[0].url;
				} else {
					cover = this.extractImageUrls(this.fileList[0])[0];
				}
				if (!cover && this.fileList[0] && this.fileList[0].url) {
					cover = this.fileList[0].url;
				}
				if (!this.name || !this.htmlData || !cover) {
					this.$refs.toast.show({
						message: '标题、内容、封面缺失！',
					});
					return;
				}
				var that = this;
				let data = {
					type: this.tabbarsValue,
					name: this.name,
					id: this.value,
					cover: cover,
					tags: this.tagNormalizer(this.tags),
					api: this.type,
					link: this.link,
					custom: this.custom
				};
				if (e) {
					data['chat'] = a;
				}
				if (this.sInfo) {
					data['des'] = this.htmlData;
				} else {
					data['content'] = this.htmlData;
					data['des'] = this.des;
				}
				return data;
			},
			async confirm(e = null, a = null) {
				try {
					var data = await this.datahand(e, a);
					if (!data) {
						return;
					};
					this.aesDate = Md5(JSON.stringify(data));
					this.disabled = true;
					let es = await scrollName('addModify', data, {
						custom: {
							auth: true,
							catch: false,
						}
					})
					if (es._id) {
						this.updateValue(es._id);
					}
					this.$emit('refresh', uni.$uv.guid(20));
					this.disabled = false;
					this.$refs.toast.show({
						message: '保存成功！',
					})
					return true;
				} catch (e) {
					console.log(e)
					this.$refs.toast.show({
						message: '保存失败！',
					})
					this.disabled = false;
					return false;
					//TODO handle the exception
				}
			},
			/**
			 * 获取输入内容
			 * @param {Object} e {html,text} 内容的html文本，和text文本
			 */
			inputOver(e) {
				// 可以在此处获取到编辑器已编辑的内容
				// console.log('==== inputOver :', e)
				this.htmlData = e.html;
				// if (this.inputSave) uni.$uv.debounce(this.confirm, 1500);
			},
			inputFocus() {
				this.inputSave = true;
				this.$emit('focus');
			},
			inputBlur() {
				this.inputSave = false;
			},
			/**
			 * 超出最大内容限制
			 * @param {Object} e {html,text} 内容的html文本，和text文本
			 */
			overMax(e) {
				// 若设置了最大字数限制，可在此处触发超出限制的回调
				console.log('==== overMax :', e)
			},
			/**
			 * 编辑器就绪
			 * @param {Object} editor 编辑器实例，你可以自定义调用editor实例的方法
			 * @tutorial editor组件 https://uniapp.dcloud.net.cn/component/editor.html#editor-%E7%BB%84%E4%BB%B6
			 * @tutorial 相关api https://uniapp.dcloud.net.cn/api/media/editor-context.html
			 */
			initEditor(editor) {
				this.editorIns = editor // 保存编辑器实例
				// 保存编辑器实例后，可以在此处获取后端数据，并赋值给编辑器初始化内容
				// this.preRender();
			},
			preRender(data = {}) {
				var that = this;
				this.resetEditor();
				if (Object.keys(data).length === 0) {
					return;
				}
				// 异步初始化，确保编辑器实例已创建
				setTimeout(() => {
					if (data.cover) {
						that.cover = [{
							url: data.cover
						}];
					}
					if (data.type != 'fusion') {
						that.fileList = that.uv_video(data)[0] ? that.uv_video(data) : that
							.uv_image(data);
					}
					const content = that.sInfo ? data.des : (data.content?.[0] || '');
					that.editorIns?.setContents({
						html: content
					});
					that.htmlData = content;
					that.link = (data.link && data.link[0] && data.link[0].title) ? data
						.link : [{
							title: '',
							url: ''
						}];
					that.name = data.name || '';
					that.des = data.des || '';
					that.tags = data.tags || [];
					that.dynamicTags = that.tags.join(',');
					that.custom = data.custom || [];
					if (data?.custom && data.custom[0]) {
						that.uploads = data.custom;
					};
				}, 500);
			},
			// 重置编辑器内容
			resetEditor() {
				let html = '';
				for (var index = 0; index < 0; index++) {
					html = html + 1;
				}
				var that = this;
				setTimeout(() => {
					that.editorIns?.setContents({
						html: html
					});
					that.htmlData = '';
					that.name = '';
					that.des = '';
					that.link = [{
						title: '',
						url: ''
					}];
					that.tags = [];
					that.dynamicTags = '';
					that.fileList = [];
					that.custom = [];
					that.cover = [];
					that.uploads = [];
					// that.referImages = [];
				}, 500);
			},
			uploadFile(e, editorCtx) {
				this.only = e;
				this.$nextTick(() => {
					this.$refs.document.visible();
				});
				this.editorCtx = editorCtx;
			},
			// /**
			//  * 直接运行示例工程插入图片无法正常显示的看这里
			//  * 因为插件默认采用云端存储图片的方式 
			//  * this.$emit('upinVideo', tempFilePath, this.editorCtx, this.editorId)
			//  * 以$emit('upinImage', tempFiles, this.editorCtx)的方式回调
			//  * @param {Object} tempFiles
			//  * @param {Object} editorCtx
			//  */
			// upinImage(tempFiles, editorCtx) {
			// 	/**
			// 	 * 本地临时插入图片预览
			// 	 * 注意：这里仅是示例本地图片预览，因为需要将图片先上传到云端，再将图片插入到编辑器中
			// 	 * 正式开发时，还请将此处注释，并解开下面 使用 uniCloud.uploadFile 上传图片的示例方法 的注释
			// 	 * @tutorial https://uniapp.dcloud.net.cn/api/media/editor-context.html#editorcontext-insertimage
			// 	 */
			// 	// // #ifdef MP-WEIXIN
			// 	// // 注意微信小程序的图片路径是在tempFilePath字段中
			// 	// editorCtx.insertImage({
			// 	// 	src: tempFiles[0].tempFilePath,
			// 	// 	width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
			// 	// 	success: function() {}
			// 	// })
			// 	// // #endif

			// 	// // #ifndef MP-WEIXIN
			// 	// editorCtx.insertImage({
			// 	// 	src: tempFiles[0].path,
			// 	// 	width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
			// 	// 	success: function() {}
			// 	// })
			// 	// // #endif
			// 	/**
			// 	 * 使用 uniCloud.uploadFile 上传图片的示例方法（可适用多选上传）
			// 	 * 正式开发环境中，请将上面 本地临时插入图片预览 注释后，模仿以下写法
			// 	 */
			// 	tempFiles.forEach(async (item) => {
			// 		uni.showLoading({
			// 			title: '上传中请稍后',
			// 			mask: true
			// 		})
			// 		// let upfile = await uniCloud.uploadFile({
			// 		// 	filePath: item.path,
			// 		// 	// 同名会导致报错 policy_does_not_allow_file_overwrite
			// 		// 	// cloudPath可由 想要存储的文件夹/文件名 拼接，若不拼文件夹名则默认存储在cloudstorage文件夹中
			// 		// 	cloudPath: `cloudstorage/${item.name}`,
			// 		// 	cloudPathAsRealPath: true
			// 		// })
			// 		let upfile = await uploadFile('', {
			// 			custom: {
			// 				auth: true,
			// 				catch: true
			// 			},
			// 			name: 'image',
			// 			filePath: item.path,
			// 			formData: {
			// 				type: 'image'
			// 			},
			// 		})
			// 		console.log(editorCtx);
			// 		editorCtx.insertImage({
			// 			src: upfile.url,
			// 			width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
			// 			success: function() {
			// 				uni.hideLoading()
			// 			}
			// 		})
			// 	})
			// },
			/**
			 * 导出 - toolbar需要开启export工具
			 * @param {string} e 导出的html内容
			 */
			exportHtml(e) {
				var that = this;
				this.confirm();
				// console.log(this.getImgSrc(e));
				// console.log('exportHtml', e);
				// var that = this;
				// uni.navigateTo({
				// 	url: '/pages/article/index',
				// 	success(res) {
				// 		// 传至导出页面解析即可
				// 		uni.$emit('e-transmit-html', e);
				// 	}
				// })
			},
			/**
			 * 添加超链接
			 * @param {Object} e { text: '链接描述', href: '链接地址' }
			 */
			addLink(e) {
				console.log('==== addLink :', e)
			},
			replaced(text) {
				if (!text) return;
				if (typeof text !== 'string') {
					text = text[0].text
				}
				const msgs = text.split(' --');
				if (msgs) {
					// console.log(array);
					text = msgs[0];
				}
				text = text.replace(/(```[\s\S]*?```)/g, '<pre class="code-block">$1</pre>');
				text = text.replace(/(```\b\w+\b)/g,
					'<div class="copy-text" style="display: flex;justify-content: space-between;"><span style="font-weight: bold;font-size: 15px;color:#ababab">$1</span>复制</div>'
				);
				text = text.replace(/```/g, '');
				text = text.replace(/(###[\s\S]*?\\n)/g,
					'<span style="font-weight: bold;color:#00000">$1</span>'
				);
				text = text.replace(/(###[\s\S]*?\n)/g,
					'<span style="font-weight: bold;color:#00000">$1</span>'
				);
				text = text.replace(/###/g, '');
				text = text.replace(/\\n/g, "<br>");
				text = text.replace(/\n/g, "<br>");
				text = text.replace(/<article[^>]*>/g, '<p>').replace(/<section[^>]*>/g, '<p>');
				// text && text.replace(/(\s{2,})(?![^<>]*>)/g, function(
				// 	match) {
				// 	return match.replace(/ /g, '&nbsp;');
				// });
				return text;
			},
			routed(url) {
				uni.$uv.route({
					url: url
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	@import '/uni_modules/sp-editor/icons/custom-icon.css';
	@import '/uni_modules/sp-editor/icons/editor-icon.css';

	::v-deep ::-webkit-scrollbar {
		/* 滚动条整体样式 */
		display: block !important;
		width: 7rpx !important;
	}

	::v-deep ::-webkit-scrollbar-thumb {
		/* 滚动条里面小方块 */
		border-radius: 5rpx !important;
		box-shadow: inset 0 0 1rpx rgba(0, 0, 0, 0.2) !important;
		background-color: #CCCCCC !important;
	}

	.article-editor {
		overflow: auto;
		margin: 1px 5px;

		height: auto;
		max-width: 850px !important;
		// margin-right: 10px;

		// display: block;
		// width: 10px !important;
		// height: 10px !important;
		// -webkit-appearance: block;
		// background: #eeeeee;

		.editor-box {
			// width: 100%;
			display: block;
			border: 1px solid #ddd;
			border-radius: 10px;

			::v-deep .uni-input-placeholder {
				overflow: visible;
			}
		}

		.editor-tag {
			border-top: 1px solid #ddd;

			.uv-page__tag-item {
				margin-right: 15px;
				margin-bottom: 10px;
			}

			.el-tag+.el-tag {
				margin-left: 10px;
			}

			.button-new-tag {
				margin-left: 10px;
				height: 32px;
				line-height: 30px;
				padding-top: 0;
				padding-bottom: 0;
			}

			.input-new-tag {
				width: 90px;
				margin-left: 10px;
				vertical-align: bottom;
			}
		}

		.editor-button {
			border-top: 1px solid #ddd;
			padding: 5px;
			display: flex;
			justify-content: space-evenly;
			align-items: center;

			// background-color: #eee;
			.editor-button_right {
				display: flex;
			}

			.editor-button_left {
				font-size: 13px;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				color: #5AC725;
			}
		}

		.uvUpload {
			::v-deep .uv-upload__button {
				display: none;
			}

			::v-deep .uv-upload__wrap {
				margin: 0px;
			}

			// ::v-deep .uv-upload__wrap__preview{
			// 	margin-right: 10px;
			// }
		}

		.item_dsh {
			position: absolute;
			z-index: 10;
			top: -6px;
			right: -6px;
			color: #fff;
			background-color: #000;
			padding: 3px 3px;
			// border-top-right-radius: 10px;
			// border-bottom-left-radius: 10px;
			border-radius: 6px;
			cursor: pointer;
			border: 1px solid #fff;
		}

		.uploadImage {
			cursor: pointer;
			border-radius: 10px;
			color: #666;
			font-size: 15px;
		}

		.uploadImage:hover {
			background-color: #ECF5FF;
			color: #409EFF;
		}
	}
</style>